/**
 * Program  : CommonsUtil.java
 * Author   : qianj
 * Create   : 2012-3-23 下午03:35:56
 *
 * Copyright 2012 by newyulong Technologies Ltd.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of newyulong Technologies Ltd.("Confidential Information").  
 * You shall not disclose such Confidential Information and shall 
 * use it only in accordance with the terms of the license agreement 
 * you entered into with newyulong Technologies Ltd.
 *
 */

package com.newyulong.implatform.util;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.newyulong.implatform.IMPApplication;
import com.newyulong.implatform.R;

/**
 * 常用的一些工具
 * 
 * @author qianj
 * @version 1.0.0
 * @2012-3-23 下午03:35:56
 */
public class CommonsUtil {

	private static final String TAG = "CommonsUtil.class";
	public static Message msg = null;

	/**
	 * 提示信息的通用dialog
	 * @param paramActivity
	 * @param text
	 * @return
	 */
	public static void createInfoDialog(Activity paramActivity,
			String text) {
		AlertDialog.Builder builder = new Builder(paramActivity);
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setMessage(text);
		builder.setTitle("提示");
		builder.setPositiveButton("确定", null);
		builder.create().show();
		
	}
	
	/**
	 * 创建进度dialog
	 * @param context
	 * @param msg
	 */
	public static ProgressDialog createProgressDialog(Context context,String msg){
		ProgressDialog pd = new ProgressDialog(context);
		pd.setMessage(msg);
		pd.setCanceledOnTouchOutside(false);
		pd.setCancelable(false);
		return pd;
	}
	
	
	/**
	 * 得到自定义的progressDialog
	 * @param context
	 * @param msg
	 * @return
	 */
	public static Dialog createLoadingDialog(Context context,String msg){
		
		LayoutInflater inflater = LayoutInflater.from(context);
		View v = inflater.inflate(R.layout.loading_dialog, null);//得到加载view
		LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);//加载布局
		// main.xml中的ImageView
		ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
		TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);//提示文字
		// 加载动画
		Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(context,
				R.anim.load_animation);
		// 使用ImageView显示动画
		spaceshipImage.startAnimation(hyperspaceJumpAnimation);
		tipTextView.setText(msg);//设置加载信息
		
		Dialog loadingDialog = new Dialog(context,R.style.FullHeightDialog);//创建自定义样式dialog
		
		loadingDialog.setCancelable(true);//可以取消
		loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT));//设置布局
		return loadingDialog;
		
	}
	

	/**
	 * 由图片URL得到图片 这个方法效率好像还有点问题
	 * 
	 * @author qianj
	 * @create 2012-3-26 上午11:34:01
	 * @since
	 * @param imgUrl
	 * @return
	 */
	public static Drawable getIconImage(String imgUrl) {
		Drawable drawable = null;
		try {
			URL url = new URL(imgUrl);
			drawable = Drawable.createFromStream(url.openStream(), "src");
		} catch (Exception e) {
			Log.i(TAG, "由URL得到图片时异常！");
			e.printStackTrace();
		}
		return drawable;
	}

	/**
	 * 另一种由URL得到图片 这个方法效率好像还有点问题
	 * 
	 * @author qianj
	 * @create 2012-3-26 上午11:50:56
	 * @since
	 * @param imgUrl
	 * @return
	 */
	public static BitmapDrawable getPic(String imgUrl) {
		BitmapDrawable bd = null;
		try {
			URL url = new URL(imgUrl);
			// 建立网络连接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 获取图片输入流
			InputStream is = conn.getInputStream();
			bd = new BitmapDrawable(is);// 使用输入流对象创建一个bitmapdrawable
			conn.disconnect();// 关闭网络连接
		} catch (Exception e) {
			Log.i(TAG, "由URL得到图片时异常！");
			e.printStackTrace();
		}
		return bd;
	}

	/**
	 * 得到http请求发送的URL
	 * 
	 * @author qianj
	 * @create 2012-3-30 上午10:38:08
	 * @since
	 * @return
	 */
	public static String getRequestUrl() {
		return IMPApplication.getInstance().getRequestUrl();
	}

	/**
	 * 得到listview的底部
	 * @author qianj
	 * @create 2012-3-31 下午02:20:40
	 * @since
	 * @return
	 */
	public static LinearLayout getListViewFooter(Context context) {

		LayoutParams mTipContentLayoutParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);

		LinearLayout mLoadLayout = new LinearLayout(context);
		mLoadLayout.setMinimumHeight(50);
		mLoadLayout.setGravity(Gravity.CENTER);
		mLoadLayout.setOrientation(LinearLayout.HORIZONTAL);
		
		/**
		 * 向"加载项"布局中添加提示信息。
		 */
		TextView mTipContent = new TextView(context);
		mTipContent.setText("点击加载更多");
		mLoadLayout.addView(mTipContent, mTipContentLayoutParams);

		return mLoadLayout;
	}

	/**
	 * 得到用户电话
	 * 
	 * @author qianj
	 * @create 2012-4-11 下午03:09:16
	 * @since
	 * @return
	 */
	public static String getPhoneNum(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		// String imei = tm.getDeviceId();
		return tm.getLine1Number();
	}

	
	/**
	 * @param regex
	 *            正则表达式字符串
	 * @param str 要匹配的字符串
	 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
	 */
	private static boolean match(String regex, String str) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}

	/**
	 * 判断手机号码是否合法
	 * @param phoneNum
	 * @return
	 */
	public static boolean isPhoneNum(String phoneNum) {
		String regex = "^1(4[5]|3[0-2]|5[56]|8[56])\\d{8}$";
		return match(regex, phoneNum);
	}
	
	/**
	 * 判断当前网络状态
	 * @param context
	 * @return
	 */
	public static boolean checkNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						NetworkInfo netWorkInfo = info[i];
						if (netWorkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
							return true;
						} else if (netWorkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
							return true;
						}
					}
				}
			}
		}
		return false;
	}

	
	
	
	

	/** 
	 * 返回当前程序版本名 
	 */  
	public static String getAppVersionName(Context context) {  
	    String versionName = "";  
	    try {  
	        // ---get the package info---  
	        PackageManager pm = context.getPackageManager();  
	        PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);  
	        versionName = pi.versionName;  
	        if (versionName == null || versionName.length() <= 0) {  
	            return "";  
	        }  
	    } catch (Exception e) {  
	        Log.e("VersionInfo", "Exception", e);  
	    }  
	    return versionName;  
	}  
	
	

}
